/*
 * Copyright (c) 2019 DawnFramework. All Rights Reserved.
 * Licensed under the MIT (LICENSE) license.
 */

package org.dawn.common.web.res;

import lombok.Getter;
import org.dawn.common.core.except.IError;
import org.dawn.common.web.model.PageModel;

import java.util.List;

/**
 * 用于兼容 Controller 层返回统一数据模型的场景。建议异常码用 http status code 替代，Response body 直接返回 PageView 模型。
 *
 * @author Willard Hu on 2019-05-19.
 */
@Getter
public class JsonPageResult extends PageModel {
    private static final long serialVersionUID = -4605580924298564437L;
    private Boolean success;
    private String code;
    private String message;

    /** 屏蔽构造函数 */
    private JsonPageResult() {
    }

    public static Builder newBuilder(int page, int rows) {
        return new Builder(page, rows);
    }

    public static class Builder extends PageModel {
        private static final long serialVersionUID = 369602962323399032L;

        private Boolean success;
        private String code;
        private String message;

        /** 屏蔽构造函数 */
        private Builder(int page, int rows) {
            this.page = page;
            this.rows = rows;
        }

        public Builder succ(List<?> model, int totalCount, int totalPage) {
            this.success = true;
            this.model = model;
            this.totalCount = totalCount;
            this.totalPage = totalPage;
            return this;
        }

        public Builder fail(String code, String message) {
            this.code = code;
            this.message = message;
            this.success = false;
            return this;
        }

        public Builder fail(IError<?> error) {
            this.code = String.valueOf(error.errcode());
            this.message = error.errmsg();
            this.success = false;
            return this;
        }

        public JsonPageResult build() {
            JsonPageResult res = new JsonPageResult();
            res.success = this.success;
            res.code = this.code;
            res.message = this.message;

            res.page = this.page;
            res.rows = this.rows;
            res.totalCount = this.totalCount;
            res.totalPage = this.totalPage;
            res.model = this.model;
            return res;
        }
    }
}
